const app = require('./app.json')
const config = require('./config').config
const exec = require('child_process').exec
// Gulp Core
const gulp = require('gulp')
// Javascript
const babel = require('gulp-babel')
const jsMin = require('gulp-uglify')
const tsc = require('gulp-typescript')
// Css
const cssMin = require('gulp-clean-css')
const autoprefixer = require('gulp-autoprefixer')
const sass = require('gulp-sass')
// Html
const ejs = require('gulp-ejs')
const replace = require('gulp-replace')
// Other
const fs = require('fs')
// const del = require('del');
const fpath = require('path')
const watch = require('gulp-watch')
const rename = require('gulp-rename')
const imgMin = require('gulp-imagemin')
const plumber = require('gulp-plumber')
// BrowserSync
const browserSync = require('browser-sync').create()
const dproxy = require("http-proxy-middleware")
const reload = () => {}
// browserSync.reload

// Start Server
var pathRewrite = {}
pathRewrite['^' + config.proxy.dir] = config.proxy.dir
let browserSyncOption = {
  files: ['project/**/**/**/**/**/**/**/**/*.*'],
  server: {
    baseDir: './build',
    middleware: dproxy(config.proxy.dir, {
      target: config.proxy.url,
      logLevel: 'warn',
      changeOrigin: true,
      pathRewrite: pathRewrite
    })
  },
  open: 'external',
  ghostMode: config.server.ghost
}
browserSync.init(browserSyncOption)

console.clear()
// Tasks
var path = 'project/**/**/**/**/**/**/**/**/**'

gulp.task('default', ['sync', 'js', 'sass', 'css', 'image', 'html'], () => {
  if (fs.existsSync('.BUILD_MODE')) {
    setTimeout(() => {
      process.exit()
    }, 15000)
    return false;
  }
  // sync
  gulp.watch([path], ['sync'])
  // Js
  gulp.watch([`${path}.js`,`${path}.ts`], ['js'])
  // Css
  gulp.watch(`${path}.css`,['css'])
  gulp.watch(`${path}.scss`,['sass', 'css', 'html'])
  // Html
  gulp.watch([`${path}.html`,`${path}.ejs`], ['html'])
  // Image
  gulp.watch([`${path}.png`,`${path}.jpg`,`${path}.jpeg`, `${path}.gif`], ['image'])
  // File
  watch(path).on('unlink', (file) => {
    let buildFile = './build/' + fpath.relative('./project', file)
    let fsStat = fs.statSync(buildFile)
    if (fsStat.isFile()) {
      fs.unlinkSync(buildFile)
    }
    if (fsStat.isDirectory()) {
      exec(`rm -rf ${buildFile}`, () => {})
    }

  })
  console.clear()
})

// Task: Sync File
gulp.task('sync', () => {
  console.log('[Task] Sync File')
  gulp.src([path, `!${path}.scss`, `!${path}.html`, `!${path}.js`, `!${path}.css`])
      .pipe(gulp.dest('build'))
  console.log('[Task] File Synced')
})

// Task: Js Builder
gulp.task('js', () => {
  console.log('[Task] Js Building')
  gulp.src(`${path}.js`)
      .pipe(plumber())
      .pipe(babel({
        presets: [
          ['es2015', { modules: false, loose: true }]
        ]
      }))
      .pipe(gulp.dest('build'))

  console.log('[Task] Js Builded')
})

// Task: Css Builder
gulp.task('css', () => {
  console.log('[Task] Css Building')
  let src = gulp.src(`${path}.css`)
                .pipe(plumber())
                .pipe(autoprefixer())
  if (config.min.css) {
    src = src.pipe(cssMin())
  }
  src.pipe(gulp.dest('build'))

  console.log('[Task] Css Builded')
})
gulp.task('sass', () => {
  src = gulp.src(`${path}.scss`)
            .pipe(plumber())
            .pipe(sass())
            .pipe(autoprefixer())
            .pipe(rename({extname: '.css'}))
            .pipe(gulp.dest('build'))

})

// Task: Image Compress
gulp.task('image', () => {
  console.log('[Task] Image Compressing')
  gulp.src([`${path}.png`, `${path}.jpg`, `${path}.jpeg`, `${path}.gif`])
      .pipe(plumber())
      .pipe(imgMin())
      .pipe(gulp.dest('build'))

  console.log('[Task] Image Compressed')
})

// Task: Html Builder
gulp.task('html', () => {
  console.log('[Task] Html Builder')
  let version = new Date().getTime()
  gulp.src(`${path}.html`)
      .pipe(plumber())
      .pipe(replace(/src="(.*?)\.js\?(.*?)"/gi, `src="$1.js?_v=${version}&$2"`))
      .pipe(replace(/src="(.*?)\.js"/gi, `src="$1.js?_v=${version}"`))
      .pipe(replace(/href="(.*?)\.scss\?(.*?)"/gi, `href="$1.css?_v=${version}&$2"`))
      .pipe(replace(/href="(.*?)\.scss"/gi, `href="$1.css?_v=${version}"`))
      .pipe(replace(/href="(.*?)\.css\?(.*?)"/gi, `href="$1.css?_v=${version}&$2"`))
      .pipe(replace(/href="(.*?)\.css"/gi, `href="$1.css?_v=${version}"`))
      .pipe(replace(/<html /gi, `<!--  Automatic processing ${new Date().getTime()} -->\r\n<html `))
      .pipe(ejs(app))
      .pipe(gulp.dest('build'))

  console.log('[Task] Html Builded')
})
